package com.basker.pisces.service.exception;

import java.util.List;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.basker.pisces.core.helper.DataContractHelper;

public interface IObjectErrorsWrapper extends IServiceErrorResult {

    List<ObjectError> getErrors();

    default boolean hasErrors() {
        return !CollectionUtils.isEmpty(getErrors());
    }

    ;

    /**
     * 表示一个对象的错误详情
     *
     * @author hangwen
     */
    public static class ObjectError {

        private transient Object object;
        private String objectName;
        private String errorCode = "-1";
        private String errorMessage;

        public ObjectError(String errorCode, Object object, String objectName, String errorMessage) {
            this.errorCode = errorCode;
            this.object = object;
            this.objectName = objectName;
            this.errorMessage = errorMessage;

            if (this.objectName == null && this.object != null) {
                this.objectName = DataContractHelper.toString(object);
            }
        }

        public static String joinErrorMessage(List<ObjectError> errors) {
            if (CollectionUtils.isEmpty(errors)) {
                return "";
            }

            return String.join(",", errors.stream().map(error -> error.toString()).toArray(l -> new String[l]));
        }

        /**
         * 错误码
         *
         * @return
         */
        public String getErrorCode() {
            return errorCode;
        }

        /**
         * 错误消息
         *
         * @return
         */
        public String getErrorMessage() {
            return errorMessage;
        }

        /**
         * 错误对象
         *
         * @return
         */
        public Object getObject() {
            return object;
        }

        /**
         * 显示设置错误对象
         *
         * @param object
         */
        public void setObject(Object object) {
            this.object = object;
        }

        /**
         * 错误对象的名称
         *
         * @return
         */
        public String getObjectName() {
            return objectName;
        }

        /**
         * 显示设置错误对象的描述
         *
         * @param objectName
         */
        public void setObjectName(String objectName) {
            this.objectName = objectName;
        }

        @Override
        public String toString() {
            if (StringUtils.isEmpty(this.objectName)) {
                return this.errorMessage;
            }

            return this.objectName + ":" + this.errorMessage;
        }

    }
}
